package com.topvision.jack.uploadlibrary.utils;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.text.TextUtils;

public class BlueToothUtil {

    /**
     * 获取蓝牙地址
     *
     * @param @param internal 尝试连接蓝牙次数
     * @return String 返回mac地址字符串
     * @throws
     * @Title: getBtMacAdress
     * @Description:
     */
    public static String getBtMacAdress(Context context, int internal) {
        BluetoothAdapter bAdapt = BluetoothAdapter.getDefaultAdapter();
        String btMac = "";
        if (bAdapt != null) {
            // 获取蓝牙mac地址
            // btMac = bAdapt.getAddress();
            btMac = getBtMac(context);
        } else {
            btMac = "";
        }
        // 没有蓝牙的情况和打开蓝牙了并获取了蓝牙mac地址情况
        if (!TextUtils.isEmpty(btMac) || bAdapt == null) {
            return btMac;
        }
        boolean isOkBt = false;
        // 如果原先情??牙?有打?
        if (!bAdapt.isEnabled()) {
            // 尝试打开
            isOkBt = tryOpenBt(bAdapt);
        }
        for (int index = 0; index < internal; index++) {
            // 如果第一次没有成功，第二次做100毫秒的延迟。
            if (index != 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            btMac = getBtMac(context);
            if (!TextUtils.isEmpty(btMac)) {
                break;
            }
        }

        // 尝试关闭蓝牙
        if (isOkBt) {
            tryCloseBt(bAdapt);
        }
        return btMac;
    }

    private static boolean tryCloseBt(BluetoothAdapter bAdapt) {
        return bAdapt.disable();
    }

    /**
     * 尝试打开蓝牙
     */
    private static boolean tryOpenBt(BluetoothAdapter adapter) {
        return adapter.enable();
    }


    /**
     * 获取bt mac 地址没有冒号的字符串信息
     *
     * @param @return
     * @return String
     * @throws
     * @Title: getBtMacNoColons
     * @Description:
     */
    public static final String getBtMacNoColons(Context context) {
        String btMac = getBtMacAdress(context, 10);
        if (!TextUtils.isEmpty(btMac)) {
            //对btmac去除:,有效的别名、标签组成：字母（区分大小写）、数字、下划线、汉字
            String newAlinas = "";
            String[] tempArray = btMac.split(":");
            for (String str : tempArray) {
                newAlinas += str;
            }
            //重新赋值
            btMac = newAlinas;
            return btMac;
        }
        return "";
    }


    /**
     * 获取手机的MAC地址
     *
     * @return
     */
    public static String getBtMac(Context context) {
        String macAddress = android.provider.Settings.Secure.getString(context.getContentResolver(), "bluetooth_address");
        return macAddress;
    }
}
